package com.cicc.beergamevirtualsimulationsystem.common.webSocket.config;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;

import com.cicc.beergamevirtualsimulationsystem.common.webSocket.holder.WebSocketSessionHolder;
import com.cicc.beergamevirtualsimulationsystem.common.webSocket.message.JsonWebSocketMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * @author Hccake 2021/1/4
 * @version 1.0
 */
@Slf4j
public class WebSocketMessageSender {
	//发送消息给指定房间
	public static void sendMessageToRoom(String roomId, String message) {
		Set<WebSocketSession> sessionsByRoom = WebSocketSessionHolder.getSessionsByRoom(roomId);
		if (CollectionUtils.isNotEmpty(sessionsByRoom)) {
			for (WebSocketSession session : sessionsByRoom) {
				try {
					session.sendMessage(new TextMessage(JSONUtil.toJsonStr(message)));
				} catch (IOException e) {
					log.error("发送消息失败", e);
				}
			}
		}
	}
	//发送消息给指定房间
	public static void sendMessageToRoom(String roomId, JsonWebSocketMessage message) {
		Set<WebSocketSession> sessionsByRoom = WebSocketSessionHolder.getSessionsByRoom(roomId);
		if (CollectionUtils.isNotEmpty(sessionsByRoom)) {
			for (WebSocketSession session : sessionsByRoom) {
                send(session, message);
//					session.sendMessage(new TextMessage(JSONUtil.toJsonStr(message)));
            }
		}
	}

	//发送消息给已选择角色的用户和未选择角色的用户
	public static void sendMessageToSelectedUser(String roomId, JsonWebSocketMessage trueMessage, JsonWebSocketMessage falseMessage, Set<String> ids) {
		Set<WebSocketSession> sessionsByRoom = WebSocketSessionHolder.getSessionsByRoom(roomId);
		if (CollectionUtils.isNotEmpty(sessionsByRoom)) {
			for (WebSocketSession session : sessionsByRoom) {
				// 已选择角色
				if (ids.contains(session.getAttributes().get("userId"))) {
					send(session, trueMessage);
				}else {
					// 未选择角色
					send(session, falseMessage);
				}
			}
		}

	}

	//发送消息给指定用户
	public static void send(WebSocketSession session, JsonWebSocketMessage message) {
		send(session, JSONUtil.toJsonStr(message));
	}



	public static boolean send(WebSocketSession session, String message) {
		if (session == null) {
			log.error("[send] session 为 null");
			return false;
		}
		if (!session.isOpen()) {
			log.error("[send] session 已经关闭");
			return false;
		}
		try {
			session.sendMessage(new TextMessage(message));
		}
		catch (IOException e) {
			log.error("[send] session({}) 发送消息({}) 异常", session, message, e);
			return false;
		}
		return true;
	}

}
